package com.rawchen.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rawchen.config.RedisKeyConfig;
import com.rawchen.entity.About;
import com.rawchen.exception.PersistenceException;
import com.rawchen.mapper.AboutMapper;
import com.rawchen.service.AboutService;
import com.rawchen.service.RedisService;
import com.rawchen.util.markdown.MarkdownUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 关于我页面业务层实现
 */
@Service
public class AboutServiceImpl extends ServiceImpl<AboutMapper, About> implements AboutService {
	@Autowired
	private AboutMapper aboutMapper;
	@Autowired
	private RedisService redisService;

	@Override
	public Map<String, String> getAboutInfo() {
		// 现在redis中找，如果有就直接返回
		String redisKey = RedisKeyConfig.ABOUT_INFO_MAP;
		Map<String, String> aboutInfoMapFromRedis = redisService.getMapByValue(redisKey);
		if (aboutInfoMapFromRedis != null) {
			return aboutInfoMapFromRedis;
		}
		Map<String, String> aboutInfoMap = new HashMap<>();

		aboutMapper.selectList(null).forEach(about -> {
			if ("content".equals(about.getNameEn())) {
				about.setValue(MarkdownUtils.markdownToHtmlExtensions(about.getValue()));
			}
			aboutInfoMap.put(about.getNameEn(), about.getValue());
		});
		redisService.saveMapToValue(redisKey, aboutInfoMap);
		return aboutInfoMap;
	}

	@Override
	public Map<String, String> getAboutSetting() {
		List<About> abouts = aboutMapper.selectList(null);
		Map<String, String> map = new HashMap<>();
		for (About about : abouts) {
			map.put(about.getNameEn(), about.getValue());
		}
		return map;
	}

	@Override
	public void updateAbout(Map<String, String> map) {
		for (Map.Entry<String, String> entry : map.entrySet()) {
			updateOneAbout(entry.getKey(), entry.getValue());
		}
		deleteAboutRedisCache();
	}

	@Transactional
	public void updateOneAbout(String nameEn, String value) {
		LambdaUpdateWrapper<About> luw = new LambdaUpdateWrapper<>();
		luw.set(About::getValue, value).eq(About::getNameEn, nameEn);
		if (aboutMapper.update(null, luw) != 1) {
			throw new PersistenceException("修改失败");
		}
	}

	@Override
	public boolean getAboutCommentEnabled() {
		LambdaQueryWrapper<About> lqw = new LambdaQueryWrapper<>();
		lqw.select(About::getValue).eq(About::getNameEn, "commentEnabled");
		String commentEnabledString = aboutMapper.selectOne(lqw).getValue(); //NameEn为unique键，不会抛异常
		return Boolean.parseBoolean(commentEnabledString);
	}

	/**
	 * 删除关于我页面缓存
	 */
	private void deleteAboutRedisCache() {
		redisService.deleteCacheByKey(RedisKeyConfig.ABOUT_INFO_MAP);
	}
}
